<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
<title>S-Pet Index</title>
<!-- <link type="text/css" rel="stylesheet" href="css/demo.css" /> -->
<link type="text/css" rel="stylesheet" href="css/jquery.mmenu.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.datetimepicker.css">
<link rel="stylesheet" type="text/css" href="css/1128.css">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0-rc.1/jquery.mobile.structure-1.4.0-rc.1.min.css" />
<!-- <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" /> --> 
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<!--   	<script src="http://code.jquery.com/mobile/1.4.0-alpha.2/jquery.mobile-1.4.0-alpha.2.min.js"></script> -->
	<script type="text/javascript" src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
	<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
	<script type="text/javascript" charset="utf-8" src="js/phonegap-nfc.js"></script>
	<script type="text/javascript" charset="utf-8" src="phonegap-toast.js"></script>
	<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true&libraries=places"></script>
 	<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js"></script>
    <script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/src/markermanager.js"></script>

	<script type="text/javascript" charset="utf-8" src="js/file.js"></script>
    <script type="text/javascript" charset="utf-8" src="js/read.js"></script>
	<script type="text/javascript" charset="utf-8" src="js/polygon.min.js"></script>

		
	<script type="text/javascript" src="js/jquery.mmenu.js"></script>
	<script type="text/javascript" src="js/jquery.datetimepicker.js"></script>
	<script type="text/javascript" charset="utf-8" src="js/jquery.urlshortener.js"></script>
<!-- 				<script type="text/javascript" charset="utf-8" src="js/geolocation.js"></script>
	-->	
   <script type="text/javascript">
	//ReadMode, WriteMode 변경
	var currentMode = "ReadMode"; //읽기모드 기본
	$(function() {
    	var hash = new Date().getTime();
		$('#hash').val(hash);

		showCurMode(currentMode);
		$("#tagReadBut").on("click", function() {
			currentMode = "ReadMode";
			showCurMode(currentMode);
		});
		$("#tagWriteBut").on("click", function() {
			currentMode = "WriteMode";
			showCurMode(currentMode);
		});
		//console.log("index.html =========called...")
		document.addEventListener('deviceready', onDeviceReady, false);
	})
	
 	function handleOpenURL(url) {
	    alert("찾아주셔서 감사합니다.\n(전단 페이지로 이동합니다)\n received url: " + url);
		if(url.match('goo.gl')){
			window.location.replace(url);
		}else if(url != ''){
//			window.location.replace("http://70.12.110.62:8888/view.html?i=1385347318500");
			window.location.replace(url);
		}
	}
    

/* 	$(function() {
		showCurMode(currentMode);
		$("#tagReadBut").on("click", function() {
			currentMode = "ReadMode";
			showCurMode(currentMode);
		});
		$("#tagWriteBut").on("click", function() {
			currentMode = "WriteMode";
			showCurMode(currentMode);
		});
		document.addEventListener('deviceready', onDeviceReady, false);
	}) */

	function showCurMode(curMode) {
		console.log("=========== showCurMode call....");
		$("#currentModeInfo").html("<mark>" + curMode + "</mark>");
	}

	function onDeviceReady() {
//		alert("onDeviceReady");
		enableTagReadWrite();
	}

	function enableTagReadWrite() {

		console.log("============== enableTagReadWrite");

		nfc.addNdefListener(function(nfcEvent) {

			if (currentMode == "ReadMode") {
				tagRead(nfcEvent);
			} else if (currentMode == "WriteMode") {
				//tagWrite(nfcEvent);
				tagWriteUri(nfcEvent);
			} else {

			}

		}, function() {//success callback
			if (currentMode == "ReadMode") {
//				alert("ReadMode : Waiting for Ndef Tag...");
                navigator.notification.vibrate(500);
			} else if (currentMode == "WriteMode") {
				alert("WriteMode : Waiting for Write Tag...");
                navigator.notification.beep(1);
			}
		}, function(error) {//error callback
			alert("Error adding Ndef Listener" + JSON.stringigy(error));
		});

	}

	

	function tagRead(nfcEvent) {
		console.log("ReadMode tag scanned...");
		var tag = nfcEvent.tag;
		//alert(tag);
		var ndefMsg = tag.ndefMessage;
		//alert(JSON.stringify(ndefMsg));
		console.log("ndefMsg....");
		console.log(ndefMsg);

		var result = "";

//		alert(ndefMsg[0].type);
		console.log('------------------NDEF Type : ' + ndefMsg[0].type);

		if (ndefMsg[0].type == ndef.RTD_TEXT[0]) {
			alert("text type");
			//result = nfc.bytesToString(ndefMsg[0].payload).substring(3);
			result = ndef.textHelper.decodePayload(ndefMsg[0].payload)

		} else if (ndefMsg[0].type == ndef.RTD_URI[0]) {
			//alert("uri type");
			result = ndef.uriHelper.decodePayload(ndefMsg[0].payload);
			if (result.match("i=")) {
				var vI = result.substr(result.indexOf("=")+1, 13); // ID값 13자리 추출
				alert("ID : " + vI);
				
				//ID값을 검색하여 단말 내 .txt파일 존재여부 확인,
				var chk = fSearch(vI);
//				if(chk){
					//있으면 txt에 이어서 lat,lng 저장
//				}else{
					//없으면 다른사람 태그로 인식, 전단 화면으로 이동
					var aa = result.toString().split('i=');
//					alert(aaa[0]+'\n'+aaa[1]);
//					location.href = 'http://llun.com/v.html?i=' + aaa[1];
//				}
			}else if(result.match("goo.gl")){
				var realUrl = fLongUrl(result); //fShortUrl로 주소 단축 후 ndef 타입으로 변환
				
				alert('goo.gl 단축주소를 확인 중입니다. '+realUrl);
				/* Google Shortener 시작 */
				function fLongUrl(shortLink) {
//				    $("#longUrlInfo").html("<img src='img/loading.gif'/>");
//				    var shortUrlLink = $("#shortUrl").val();
					    jQuery.urlShortener({
					        shortUrl: shortLink,
					        success: function (longUrl) {
//					            $("#shortUrlInfo").html(shortUrl);
					        	alert('복원 성공\n'+longUrl);
					        	realUrl = longUrl;
								$("#nfcInfo h3").html(fDecode(realUrl));
					        },
					        error: function(err){
//					        	$("#longUrlInfo").html(JSON.stringify(err));
					        	alert(JSON.stringify(err));
					        }
					    });
					};
					/* Google Shortener 끝 */

					setTimeout(function(){
						alert('- short : ' + result + '\n- real : '+realUrl);
						//
				var vI = realUrl.substr(realUrl.indexOf("=")+1, 13); // ID값 13자리 추출
				alert("ID : " + vI);

				//ID값을 검색하여 단말 내 .txt파일 존재여부 확인,
				var chk = fSearch(vI);
				if(chk){
					//있으면 txt에 이어서 lat,lng 저장
				}else{
					//없으면 다른사람 태그로 인식, 전단 화면으로 이동
					var aa = realUrl.toString().split('i=');
						//location.href = realUrl;
				}
						//
					}, 2000); //2초 지연			
			}else if(result.match("http")) {
				alert(result + " [URL]");
//				location.href = result;
			}
			
			
		}

		//alert(nfc.bytesToString(ndefMsg[0].payload).substring(3));
		$("#readMsg").html(result);

		$("#nfcInfo > h2").html(result);
	}
	
	
	function tagWriteUri() {
		console.log("Write Uri Mode tag detected....");
		/* 	  var vI = $("#i").val(),
	    vO = $("#o").val(),
	    vN = $("#n").val(),
	    vT = $("#t").val(),
	    vM = $("#m").val(),
	    vC = $("#c").val(), */
	    
		//html에서 저장할 값을 가져옴
		  var vI = document.forms[0].elements["i"].value;
		  var vD = document.forms[0].elements["d"].value;
		  
		  //필수입력항목들
		  var vN = document.forms[0].elements["n"].value;
		  var vO = document.forms[0].elements["o"].value;
		  var vT = document.forms[0].elements["t"].value;
		  var vM = document.forms[0].elements["m"].value;
		  var vC = document.forms[0].elements["c"].value;
		  
		  //필수입력체크
		  function fillCheck(vN, vO, vT, vM, vC){
		  		if(vN != '' && vO != '' && vT != '' && vM != '' && vC != ''){
//----------------------
		  			
		  			
		  		
/*	  var mimeType = document.forms[0].elements["mimeType"].value,
	    record = ndef.mimeMediaRecord(mimeType, nfc.stringToBytes(payload)),
*/	  //	launch = ndef.mimeMediaRecord('text/spet', nfc.stringToBytes('On')),//mimeType
//		launch = ndef.mimeMediaRecord('spetz', nfc.stringToBytes('llun.com/nfc'));

		//URL 인코드 후 url 변수에 저장
		vUrl = fEncode('i='+vI+'&d='+vD+'&o='+vO+'&n='+vN+'&t='+vT+'&m='+vM+'&c='+vC);
//		url = fEncode('http://llun.com/v.html?i='+vI+'&o='+vO+'&n='+vN+'&t='+vT+'&m='+vM+'&c='+vC);
//	    record = ndef.uriRecord('http://'+url);
		
		var tagWriteMsg = 'http://llun.com/v.html?' + vUrl;//$("#writeMsg").val();
		var vSUrl = fShortUrl(tagWriteMsg); //fShortUrl로 주소 단축 후 ndef 타입으로 변환
		
		alert('[Shortener 진입]\n태그를 떼지 마시고 잠시 기다려주세요. '+vSUrl);
		/* Google Shortener 시작 */
		function fShortUrl(longUrlLink) {
//			    $("#shortUrlInfo").html("<img src='img/loading.gif'/>");
//			    var longUrlLink = $("#longUrl").val();
			    jQuery.urlShortener({
			        longUrl: longUrlLink,
			        success: function (shortUrl) {
//			            $("#shortUrlInfo").html(shortUrl);
			        	alert('URL 단축 성공 : '+shortUrl);
			        	vSUrl = shortUrl;
			        },
			        error: function(err){
//			        	$("#shortUrlInfo").html(JSON.stringify(err));
			        	alert(JSON.stringify(err));
			        }
			    });
			};
			/* Google Shortener 끝 */

			setTimeout(function(){
				alert('Shortener 완료\n(저장 성공 메시지까지 Tap 유지)\n : '+vSUrl);
				//태그 저장 부분
				var message = [ ndef.uriRecord(vSUrl) ];
				
		 		nfc.write(message, function() {
		        toast.showShort("Wrote data to tag.");
				navigator.notification.beep(1);
				fLogWrite(tagWriteMsg); //File로 작성기록(log) 저장
				navigator.notification.alert(message);
			}, function(reason) {
				navigator.notification.alert(reason, function() {
				}, "다시 탭해주세요.");
			}); 
				//태그 저장 종료
			}, 3000); //3초 지연


/* 필수입력 체크 추가 */
				  }else{
					  var v1 = '', v2 = '', v3 = '', v4 = '', v5 = '';
					  
					  if(vN == ''){ v1 = '[동물이름]\n'; }
					  if(vO == ''){ v2 = '[색깔]\n'; }
					  if(vT == ''){ v3 = '[전화번호]\n';
					  }if(vM == ''){	v4 = '[특이사항]\n';
					  }if(vC == ''){ v5 = '[사례금]\n';
					  }					  
					  alert('다음 항목을 채워주세요!\n'+v1+v2+v3+v4+v5);
				  }
			  }
			  //필수입력 체크!
			  fillCheck(vN, vO, vT, vM, vC);
			  /* 필수입력 체크 추가 끝*/

	
			//textRecord: function (text, languageCode, id) {
			var uriRecord = ndef.uriRecord(vSUrl);
//			var uriRecord = ndef.uriRecord(tagWriteMsg);
			var message = [ uriRecord ];

/* 		nfc.write(message, function() {
	        toast.showShort("Wrote data to tag.");
			navigator.notification.beep(1);
			fLogWrite(tagWriteMsg); //log로 디바이스내 저장
			navigator.notification.alert(message);
		}, function(reason) {
			navigator.notification.alert(reason, function() {
			}, "다시 탭해주세요.");
		}); */
}

	function tagWrite() {
		console.log("Write Mode tag detected....");
		var tagWriteMsg = $("#writeMsg").val();
		alert("Write msg : " + tagWriteMsg);
		//textRecord: function (text, languageCode, id) {
		var textRecord = ndef.textRecord(tagWriteMsg, "utf-8");
		var message = [ textRecord ];

		nfc.write(message, function() {
			navigator.notification.beep(1);
			navigator.notification.alert(message);
		}, function(reason) {
			navigator.notification.alert(reason, function() {
			}, "다시 탭해주세요.");
		});

	}
    
    
    
    /* jQuery.mmenu-master */
	$(function() {
		$('#menu').mmenu({
			onClick		: {
				blockUI			: false,
				preventDefault	: function() {
					return this.rel != 'external';
				}
			}
		}, { pageSelector: 'div[data-role="page"]:first' });

		$('#menu a[rel!="external"]').on('click', function(){
				var _t = this;
				$('#menu').one('closed.mm', function(){
						$.mobile.changePage( _t.href, { transition: 'slide' });
					});
			});
	});

	$(document).on('pageshow', function( e, ui ){
			$('#menu').trigger( 'setPage', [ $(e.target) ] );
			$('#menu a').each(function(){
					if ( $.mobile.path.parseUrl( this.href ).href == window.location.href ){
						$(this).trigger( 'setSelected.mm' );
					}
				});
		});
	/* jQuery.mmenu-master */
    </script>

</head>
<body>
	<div data-role="page" id="main">
		<img alt="Logo" src="img/logo.png">
		<div data-role="header" data-theme="a">
			<a href="#menu" data-ajax="false" class="ui-link">메뉴</a>
			<h1>S-Pet v0.5.1</h1>
		</div>

		<!-- 메인화면 content 메뉴 -->
		<div data-role="content" data-theme="a">
			<ul data-role="listview">
				<li><a href="index.html#read" data-transition="flip">Read TAG</a></li>
				<li><a href="index.html#write" data-transition="flip">Write TAG</a></li>
				<li><a href="index.html#log" data-transition="slide">Log View(기록 정보)</a></li>			
				<li><a href="http://70.12.110.67:8888/sosList">SOS List(실종동물)</a></li>
				<li><a href="abc.html" rel="external">PG API</a></li>			
				<li><a href="map.html" data-transition="flow">Map Test</a></li>			
				<li><a href="index.html#test">NFC Test</a></li>			
			</ul>
		</div>
		
		<div data-role="footer" data-theme="a" style="text-align: center;">
			<a href="http://70.12.110.68:8888/log" data-icon="alert">Admin</a>
		</div>

		<!-- 페이지 로드 시 읽기모드 -->
		<script type="text/javascript">
		$('#main').on('pagebeforeshow', function(event){
 			currentMode = "ReadMode";
			showCurMode(currentMode);
		});
		</script>

	</div>

	<!-- 메인read 페이지 -->
	<div data-role="page" id="read">
        <div data-role="header" data-theme="a">
			<a href="#menu" data-ajax="false">Menu</a>
            <h1>Read Page</h1>
			<a href="index.html#main" data-icon="home" class="ui=btn-left">Main</a>
        </div>
    <h1>S-Pet NFC Reader</h1>
    <div id="tagContents">
    
<div id="nfcInfo">
	<h2>"휴대폰 뒷면에 S-Pet 태그를 탭해주십시오."</h2>
	<h3>읽은 Data</h3>
	<h1 id="tagContent"></h1>
	<h1 id="tagConvertContent"></h1>
</div>

        <div class="hidden">
            Scan a tag to being.
	       	<img src="img/nfc_logo.png">
        </div>
    </div>

		<!-- javascript 부분 -->
		<script type="text/javascript">
		$('#read').on('pagebeforeshow', function(event){
 			currentMode = "ReadMode";
			showCurMode(currentMode);
		});
		</script>

</div>

	<!-- 메인화면 write 메뉴 -->
	<div data-role="page" id="write">
		<div data-role="header">
			<a href="#menu" data-ajax="false">Menu</a>
			<h1>Write TAG</h1>
			<a href="#"	data-icon="refresh">menu1</a>
		</div>
		<div data-role="content" data-theme="a">
			<form method="GET">
				<h2>TAG에 입력할 내용을 작성 후 탭</h2>
				<input type="text" name="i" id="hash" readonly="readonly"/>
				<input type="text" name="o" class="input" placeholder="주인이름(선택입력, 닉네임 가능)" value="다희"/>
				<input type="text" name="d" class="input" placeholder="견종" value="코커스파니엘"/>
				<input type="text" name="n" class="input" placeholder="동물이름*" required="required" value="은비"/>
				<input type="text" name="t" class="input" placeholder="전화번호*" required="required" value="010-6761-1144"/>
				<input type="text" name="m" class="input" placeholder="특이사항*" required="required" value="멍멍 짖음 + ㅎㅎㅎ"/>
				<input type="text" name="r" class="input" placeholder="등록번호(15자리)" value="123421"/>
				<input type="text" name="c" class="input" placeholder="사례정보(단위: 만원, 선택입력)" value="200"/>
<!-- 				<input type="submit" value="입력완료"> -->
			</form>
		</div>	
				<input type="text" name="mimetype" class="input" placeholder="마임타입" required="required" value="text/spet"/>
				<input type="text" name="url" class="input" placeholder="URL*" required="required" value="http://llun.com/in"/>
			    <button onclick="SrcSlt();">사진 업로드</button>
	<div>
			<img id="image" style="display:none;width:290px;height:210px;" src="" align="top"/>
	</div> 
    <div id="viewport" class="viewport" style="display:none;">
      <img style="width:100%;height:240px;" id="photo" src=""/>
    </div>

		<!-- javascript 부분 -->
		<script type="text/javascript">
		$('#write').on('pagebeforeshow', function(event){
 			currentMode = "WriteMode";
			showCurMode(currentMode);
		});
		$(window).unload(function(){
			currentMode = "ReadMode";
			showCurMode(currentMode);
		});
		</script>

</div>
	<!-- 메인화면 write페이지 종료 -->


<!-- log 페이지 -->
<div data-role="page" id="log">
		<div data-role="header" data-theme="a" data-add-back-btn="true">
			<a href="#menu" data-icon="home" class="ui=btn-left">Menu</a>
			<h1>My Pet</h1>
			<a href="index.html#main" data-icon="home" class="ui=btn-right">Main</a>
		</div>
		<div data-role="content" data-theme="a" class="test">
 			<ul data-role="listview" data-inset="true" id="logList">
				<li data-role="list-divider">[App View] 로그 보기</li>
				<li>test</li>
<!-- 				<li><a href="#">
						<h3>[No.] Primary Key</h3>
						<p>(NFC Tag NDEF)</p></a>
				</li>
 -->			</ul>
		</div>
		
		<input type="button" onclick="removeFile()" value="로그삭제">

		
		<!-- javascript 부분 -->
		<script type="text/javascript">
		$('#log').on('pagebeforeshow', function(event){
			$('#logList').empty();
 			$('<ul>').attr('data-role','listview').attr('data-inset','true').attr('id','logList')
			.appendTo('.test');
 			$('<li/>').attr('data-role','list-divider').append("[App View] 로그 보기").appendTo("#logList");
			fRead();
			$('#logList').listview('refresh');
		});
		
		/* removeFile 함수 */
		function removeFile(){
			console.log("remove checkpoint 1");
			window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRVSuccess, onRVError);
		}

		function onRVSuccess(fileSystem){
			console.log("remove checkpoint 2");

			// 불러올 파일 디렉토리 지정 .
			fileSystem.root.getDirectory("AAA", {create:false, exclusive:false}, gotRVDir, onRVError);
		}

		function gotRVDir(dirEntry){
			console.log("remove checkpoint 3");
			
			/* 폴더 요소 읽어오기 */
	    	var directoryReader = dirEntry.createReader();
	    	
	    	directoryReader.readEntries(dirSuccess, onRVError);
			
			// 불러올 파일 이름 지정 
			//dirEntry.getFile("nfcTest.txt", {create: false, exclusive: false}, gotRVFileEntry, onRVError);
			
			function dirSuccess(entries){
				console.log("remove checkpoint 4");
				
	    		var i;
	    		//$('#logList').empty();
	    		
	    		for(i=0; i<entries.length; i++){
	    			//alert('파일이름: ' + entries[i].name);
	    		
	    			// 불러올 파일 이름 지정(NFC ID값으로 대체) 
	    			dirEntry.getFile(entries[i].name, null, function(fileEntry){
	    				fileEntry.remove(success, onRVError);
	    			}, onRVError);
	    		}
			}
		}

		function success(entry) {
			//alert("Removal succeeded");
			console.log("remove checkpoint 5: Removal succeeded");
			$('#logList').listview('refresh');
//			$('#logList').html('');
		}

		function onRVError(error) {
			console.log("Error removing file: " + error.code);
		}
		</script>
	</div>
<!--------------------------- log END ------------------------------->

<div data-role="content" data-theme="a" id="test">
	<h1>로딩 화면을 넣을 예정입니다.</h1>
	<h1 id=currentModeInfo>읽기모드</h1>
	<div id="nfcRead">
		<h3>읽은 Tag Data</h3>
		<textarea name="payload" id="readMsg" rows="5" cols="30"></textarea>
		<br /> <input type="button" name="tagRead" id="tagReadBut"
			value="tagRead" />
	</div>
	<div id="nfcWrite">
		<h3>Tag에 작성할 내용</h3>
		<textarea name="payload" id="writeMsg" rows="5" cols="30">http://llun.com/v</textarea>
		<br /> <input type="button" name="tagWrite" id="tagWriteBut"
			value="tagWrite" />
	</div>
</div>



		<nav id="menu">
			<ul>
				<li class="Selected"><a href="index.html">S-Pet v0.5(Home)</a></li>
				<li><a href="index.html#read">Read TAG</a></li>
				<li><a href="index.html#write">Write TAG</a></li>	
				<li><a href="http://70.12.110.67:8888/sosList">다희 서버 : SOS List</a></li>
				<li><a href="http://70.12.110.62:8888/sosList">본우 서버</a></li>
				<li><a href="http://70.12.110.68:8888/sosList">SB</a></li>
				<li><a href="jw.html">변재우</a></li>
				<li><a href="mylog.html?i=1386242646518">정다희</a></li>
				<li class="Label">External</li>
				<li><a href="tel:010-6761-1144" rel="external">Contact to Admin</a></li>
				<li><a href="read.html" data-rel="dialog">Read.html</a></li>
				<li><a href="spetw://">Write.html</a></li>
			</ul>
		</nav>

</body>
</html>